package cn.fotoit.product.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.SystemPropertyUtils;

import java.util.ArrayList;
import java.util.List;

public class ClassUtil {
    //获取包下面的所有类
    public static List<Class> doScan(String modulesPackage) throws Exception {
        List<Class> classes = new ArrayList<>();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + org.springframework.util.ClassUtils
                .convertClassNameToResourcePath(SystemPropertyUtils
                        .resolvePlaceholders(modulesPackage))
                + "/**/*.class";
        Resource[] resources = resourcePatternResolver
                .getResources(packageSearchPath);
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                classes.add(Class.forName(metadataReader
                        .getClassMetadata().getClassName()));
            }
        }
        return classes;
    }
}
